package ynu.edu.online_course.mapper;

import org.apache.ibatis.annotations.*;
import ynu.edu.online_course.entity.WatchRecord;
import java.util.List;
import java.util.Map;

@Mapper
public interface WatchRecordMapper {

    // 根据用户ID查询观看记录
    @Select("SELECT * FROM watch_record WHERE user_id = #{userId}")
    List<WatchRecord> findByUserId(@Param("userId") Long userId);

    // 插入观看记录
    @Insert("INSERT INTO watch_record (user_id, chapter_id, watch_count, watch_duration, watch_time) " +
            "VALUES (#{user.id}, #{chapter.id}, #{watchCount}, #{watchDuration}, #{watchTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertWatchRecord(WatchRecord watchRecord);

    // 统计某用户的观看总时长
    @Select("SELECT SUM(watch_duration) FROM watch_record WHERE user_id = #{userId}")
    Long getTotalWatchDurationByUserId(@Param("userId") Long userId);

    // 删除用户观看记录
    @Delete("DELETE FROM watch_record WHERE user_id = #{userId}")
    int deleteByUserId(@Param("userId") Long userId);

    // 查询章节观看时长
    @Select("SELECT chapter_id, SUM(watch_duration) AS total_duration " +
            "FROM watch_record " +
            "GROUP BY chapter_id")
    List<Map<String, Object>> getChapterWatchDurations();

    // 查询课程观看时长
    @Select("SELECT c.course_id AS courseId, SUM(wr.watch_duration) AS totalDuration " +
            "FROM watch_record wr " +
            "JOIN chapter c ON wr.chapter_id = c.id " +
            "GROUP BY c.course_id")
    List<Map<String, Object>> getCourseWatchDurations();


}
